<template>
  <div>
    <a-row>
      <a-col :span="6">
        <a-tabs :active-key="ttype">
          <a-tab-pane key="thing" tab="设备过滤">
            选择设备:<search
              @on-select-thing="onThingSelect"
              style="width: 300px"
            ></search>
          </a-tab-pane>
          <a-tab-pane key="model" tab="模型过滤"></a-tab-pane>
        </a-tabs>

        选择告警:<br />
        <!--<a-list
          bordered
          size="small"
          :data-source="alarms"
          item-layout="horizontal"
          class="alarmlist"
        >
          <a-list-item slot="renderItem" slot-scope="item, index">
            <a-space>
              <a-checkbox
                @change="onItemCheckedChange($event, item)"
                :checked="item.isChecked"
              ></a-checkbox>

              <span>{{ index + 1 }}</span>
              <span slot="title">{{ item.identifier }}</span>
              <span>{{ item.name }}</span>
            </a-space>
          </a-list-item>
        </a-list>-->
        <a-table
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :columns="columns"
          :data-source="alarms"
          :rowKey="
            (record) => {
              return record.identifier;
            }
          "
        />
      </a-col>
      <a-col :span="18">
        <a-space>
          <a-button :disabled="!canEdit" @click="refresh">刷新</a-button>
          <a-button :disabled="!canEdit" @click="save">保存</a-button>
          <a-radio-group
            style="margin-left: 10px"
            default-value="allOK"
            button-style="solid"
            v-model="sType"
            @change="onSTypeChange"
          >
            <a-radio-button value="allOK"> 不过滤 </a-radio-button>
            <a-radio-button value="allShielded"> 全部过滤 </a-radio-button>
            <a-radio-button value="everyDay"> 每日 </a-radio-button>
            <a-radio-button value="everyWeek"> 每周 </a-radio-button>
          </a-radio-group>
        </a-space>

        <a-tabs :active-key="selTab" @change="tabChange" v-if="showTab">
          <a-tab-pane
            key="everyweek"
            tab="每周过滤"
            v-if="sType === 'everyWeek'"
          >
            告警过滤时间段（选中的时间段为告警无效时间，即告警撤防时间）:<br />
            <time-picker
              v-model="timerange"
              :data="weektimeData"
              @on-clear="clearWeektime(weektimeData)"
              style="margin-top: 10px"
            ></time-picker>
          </a-tab-pane>
          <a-tab-pane key="everyday" tab="每日过滤" v-if="sType === 'everyDay'">
            告警过滤时间段（选中的时间段为告警无效时间，即告警撤防时间）:<br />
            <div>
              <time-picker
                v-model="everyrange"
                :data="everydaydata"
                @on-clear="clearWeektime(everydaydata)"
                style="margin-top: 10px"
              ></time-picker>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
  </div>
</template>
<script>
import Search from "@/components/search/Search.vue";
import TimePicker from "@/components/timepicker/TimePicker";
import weektimeData from "@/services/weekdata";
import everydaydata from "@/services/everydaydata";
import { getShield, editShield } from "@/services/alarmShield";
const columns = [
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "ID",
    dataIndex: "identifier",
  },
];
function splicing(list) {
  let same;
  let i = -1;
  let len = list.length;
  let arr = [];
  if (!len) return;
  while (++i < len) {
    const item = list[i];
    if (item.check) {
      if (item.check !== Boolean(same)) {
        arr.push(...["、", item.begin, "~", item.end]);
      } else if (arr.length) {
        arr.pop();
        arr.push(item.end);
      }
    }
    same = Boolean(item.check);
  }
  arr.shift();
  return arr.join("");
}
export default {
  computed: {
    canEdit() {
      let hasAlarms = !this.alarms || this.alarms.length != 0;
      if (hasAlarms) {
        let curAlarm = this.alarms.find((alarm) => {
          return alarm.isChecked;
        });
        return curAlarm;
      }
      return false;
    },
    timerange() {
      let timerr = this.weektimeData.map((item) => {
        return {
          id: item.row,
          week: item.value,
          value: splicing(item.child),
        };
      });
      return timerr;
    },
    everyrange() {
      let evr = this.everydaydata.map((item) => {
        return {
          id: item.row,
          week: item.value,
          value: splicing(item.child),
        };
      });
      return evr;
    },
  },
  components: {
    Search,
    TimePicker,
  },
  data() {
    return {
      ttype: "thing",
      alarms: [],
      mid: "",
      thingId: "",
      everydaydata,
      weektimeData,
      sType: "allOK",
      selTab: "weekday",
      showTab: true,
      alarmShields: [],
      columns,
      selectedRowKeys: [],
    };
  },
  methods: {
    onItemCheckedChange(event, item) {
      console.log(event, item);
      item.isChecked = event.target.checked;
    },
    getTargetID() {
      return this.ttype == "thing" ? this.thingId : thig.mid;
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      let self = this;
      this.alarms.forEach((a, index) => {
        let item = self.selectedRowKeys.find((s) => {
          return s === a.identifier;
        });
        if (item) {
          //a.isChecked = true
          self.$set(self.alarms[index], "isChecked", true);
        } else {
          //a.isChecked = false
          self.$set(self.alarms[index], "isChecked", false);
        }
      });
      if (this.selectedRowKeys?.length === 1) {
        this.refresh();
      }
    },
    refresh() {
      let self = this;
      getShield(this.ttype, this.getTargetID())
        .then((res) => {
          if (res && res.data && res.data.result) {
            console.log(res.data.result);
            let achecked = self.alarms.find((a) => {
              return a.isChecked;
            });
            let checked = null;
            //let count = 0
            checked = res.data.result.find((r) => {
              return r.alarm_id === achecked.identifier;
            });
            self.setCheck(checked);
            self.alarmShields = res.data.result;
          }
        })
        .catch(() => {
          self.alarmShields = [];
          self.sType = "allOK";
        });
    },
    setCheck(checked) {
      if (!checked) {
        this.sType = "allOK";
      }
      if (
        !checked.time_span_shield ||
        (Array.isArray(checked.time_span_shield) &&
          checked.time_span_shield.length == 0)
      ) {
        this.sType = "allOK";
      } else if (checked.time_span_shield == "ALL") {
        this.sType = "allShielded";
      } else if (
        checked.time_span_shield[0] &&
        checked.time_span_shield[0].sType === "day"
      ) {
        this.sType = "everyDay";
        this.translateTimeSpan(checked.time_span_shield);
        this.selTab = "everyday";
      } else {
        this.sType = "everyWeek";
        this.translateWeekTimeSpan(checked.time_span_shield);
        this.selTab = "everyweek";
      }
    },
    onSTypeChange(e) {
      let type = e.target.value;
      this.$nextTick(() => {
        if (type === "everyWeek") {
          console.log("-------set to --------", this.selTab);
          this.$nextTick(() => {
            this.showTab = false;
            this.$nextTick(() => {
              this.selTab = "everyweek";
              this.showTab = true;
            });
          });
        }
        if (type === "everyDay") {
          this.$nextTick(() => {
            this.showTab = false;
            this.$nextTick(() => {
              this.selTab = "everyday";
              this.showTab = true;
            });
          });
        }
      });
    },
    getAlarms() {
      let self = this;
      this.$store
        .dispatch("tmodel/refreshTModelByID", this.mid)
        .then((model) => {
          if (model?.body?.events) {
            model.body.events.forEach((a) => {
              a.isChecked = false;
            });
          }
          self.alarms = model?.body?.events;
        });
    },
    onThingSelect(uid, thing) {
      this.mid = thing.model_id;
      this.thingId = uid;
      this.getAlarms();
    },
    clearWeektime(data) {
      data.forEach((item) => {
        item.child.forEach((t) => {
          this.$set(t, "check", false);
        });
      });
    },

    tabChange(val) {
      console.log("-----------", val, this.selTab);
      this.selTab = val;
    },
    toPoint(time) {
      let parts = time.split(":");
      if (parts.length == 2) {
        let sec = 0;
        return { h: parseInt(parts[0], 10), m: parseInt(parts[1], 10), s: sec };
      } else if (parts.length == 3) {
        return {
          h: parseInt(parts[0], 10),
          m: parseInt(parts[1], 10),
          s: parseInt(parts[1], 10),
        };
      }
    },
    toTimeSpan(item) {
      let len = item.child.length - 1;
      let end, begin;
      let timespans = [];
      item.child.forEach((c, index) => {
        if (c.check) {
          if (index == len) {
            end = "23:59:59";
          } else {
            end = c.end;
          }

          if (begin === undefined) {
            begin = c.begin;
          }
        }
        if ((!c.check || index === len) && begin !== undefined) {
          timespans.push({
            sType: "day",
            begin_poit: this.toPoint(begin),
            end_point: this.toPoint(end),
          });
          begin = undefined;
          end = undefined;
        }
      });
      return timespans;
    },
    translateWeekTimeSpan(timespans) {
      console.log("(((((((((", timespans);
      let weekdaydata = JSON.parse(JSON.stringify(this.weektimeData));
      for (let i = 0; i < 7; i++) {
        for (let k = 0; k < 48; k++) {
          weekdaydata[i].child[k].check = false;
        }
      }
      timespans.forEach((t) => {
        let current = weekdaydata[t.day - 1];
        if (current) {
          for (let ci = 0; ci < 48; ci++) {
            let ptcheck = { h: parseInt(ci / 2), m: ((ci * 30) % 60) + 10 };
            let begin = t.begin_poit.h * 3600 + t.begin_poit.m * 60;
            let end = t.end_point.h * 3600 + t.end_point.m * 60;
            let check = ptcheck.h * 3600 + ptcheck.m * 60;
            if (check > begin && check < end) {
              current.child[ci].check = true;
              
            }
          }
        }
      });
      this.$set(this, "weektimeData", weekdaydata)
    },
    translateTimeSpan(timespans) {
      if (timespans) {
        let everydaydata = JSON.parse(JSON.stringify(this.everydaydata));
        for (let i = 0; i < 48; i++) {
          let ptcheck = { h: parseInt(i / 2), m: ((i * 30) % 60) + 10 };
          //let self = this;
          everydaydata[0].child[i].check = false;

          for (let t of timespans) {
            let begin = t.begin_poit.h * 3600 + t.begin_poit.m * 60;
            let end = t.end_point.h * 3600 + t.end_point.m * 60;
            let check = ptcheck.h * 3600 + ptcheck.m * 60;
            if (check > begin && check < end) {
              everydaydata[0].child[i].check = true;
              break;
            }
          }
        }
        this.$set(this, "everydaydata", everydaydata);
      }
    },

    saveAlarm(aid) {
      let shield = {
        target_type: this.ttype,
        target_id: this.getTargetID(),
        //time_span_shield: [],
        alarm_id: aid,
      };
      let timespans = [];

      if (this.sType == "allOK") {
        shield.time_span_shield = [];
      } else if (this.sType == "allShielded") {
        shield.time_span_shield = "ALL";
      } else if (this.sType == "everyDay") {
        if (this.everydaydata) {
          //let currItem
          //let begin;
          //let end;
          for (let item of this.everydaydata) {
            if (item.child) {
              timespans = this.toTimeSpan(item);
            }
          }
          shield.time_span_shield = timespans;
        }
        //shield.time_span_shield = timespans;
        console.log("****************", shield.time_span_shield);
      } else {
        if (this.weektimeData) {
          for (let i in this.weektimeData) {
            let day = this.weektimeData[i];
            if (day.child) {
              let tm;
              let tma = this.toTimeSpan(day);
              if (tma && tma.length == 1) {
                tm = tma[0];
              }
              if (tm) {
                let timespan = {
                  day: parseInt(i) + 1,
                  sType: "week",
                  begin_poit: tm.begin_poit,
                  end_point: tm.end_point,
                };
                timespans.push(timespan);
              }
            }
          }
          shield.time_span_shield = timespans;
        }
      }
      editShield(shield);
    },
    save() {
      let self = this;
      this.alarms.forEach((a) => {
        if (a.isChecked) {
          self.saveAlarm(a.identifier);
        }
      });
    },
  },
};
</script>
<style scoped>
.alarmlist {
  width: 350px;
  height: calc(100vh - 315px);
}
</style>